<template>
  <div class="lottery-container">
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      :closable="false"
      show-icon
    />
    <div class="content-wrapper">
      <!-- 历史数据区域 -->
      <div class="left-section">
        <div class="history-area">
          <div class="section-header">
            <h2>历史开奖记录</h2>
          </div>
          <el-table 
            :data="historyData"
            style="width: 100%" 
            border
            height="calc(100vh - 180px)"
          >
            <el-table-column prop="date" label="开奖日期" width="200">
              <template #default="scope">
                {{ scope.row.date.split(' ')[0] }}
              </template>
            </el-table-column>
            <el-table-column prop="period" label="期号" width="100" />
            <el-table-column label="中奖号码" min-width="280">
              <template #default="scope">
                <span v-for="num in scope.row.red" :key="num" class="ball red">
                  {{ num.toString().padStart(2, '0') }}
                </span>
                <span v-for="num in scope.row.blue" :key="num" class="ball blue">
                  {{ num.toString().padStart(2, '0') }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 预测结果区域 -->
      <div class="right-section">
        <div class="prediction-section">
          <div class="prediction-header">
            <h3>下期预测号码</h3>
            <div class="next-draw-info">
              <span>第{{ nextPeriod }}期</span>
              <span>{{ nextDrawDate }}</span>
            </div>
          </div>
          <div class="prediction-content" ref="predictionRef">
            <div v-for="(prediction, index) in predictions" :key="index" class="prediction-item">
              <div class="prediction-number">
                <span v-for="num in prediction.red" :key="num" class="ball red">
                  {{ num.toString().padStart(2, '0') }}
                </span>
                <span v-for="num in prediction.blue" :key="num" class="ball blue">
                  {{ num.toString().padStart(2, '0') }}
                </span>
              </div>
            </div>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="generateImage">下载图片</el-button>
            <el-button type="success" @click="copyImage">复制图片</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import html2canvas from 'html2canvas'
import { ElMessage } from 'element-plus'

const historyData = ref([])
const predictions = ref([])
const predictionRef = ref(null)
const error = ref('')
const nextPeriod = ref('')
const nextDrawDate = ref('')

// 计算下期开奖信息
const calculateNextDraw = () => {
  if (historyData.value && historyData.value.length > 0) {
    // 获取最新一期数据
    const lastDraw = historyData.value[0]
    // 计算下期期号
    nextPeriod.value = String(Number(lastDraw.period) + 1)
    
    // 计算下期开奖日期（大乐透每周一、三、六开奖）
    const lastDate = new Date(lastDraw.date)
    const nextDate = new Date(lastDate)
    const dayOfWeek = lastDate.getDay() // 0是周日，1是周一，以此类推
    
    // 计算下一个开奖日
    switch(dayOfWeek) {
      case 1: // 周一
        nextDate.setDate(lastDate.getDate() + 2) // 下一期在周三
        break
      case 3: // 周三
        nextDate.setDate(lastDate.getDate() + 3) // 下一期在周六
        break
      case 6: // 周六
        nextDate.setDate(lastDate.getDate() + 2) // 下一期在周一
        break
      default:
        nextDate.setDate(lastDate.getDate() + 1) // 异常情况，加一天
    }
    
    // 格式化日期
    nextDrawDate.value = nextDate.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      weekday: 'long'
    })
  }
}

// 获取历史数据
const fetchHistoryData = async () => {
  try {
    const response = await fetch('/api/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=200&isVerify=1')
    const data = await response.json()
    console.log('API返回的原始数据:', data)
    if (!data.value || !data.value.list) {
      throw new Error('API返回数据格式错误')
    }
    
    historyData.value = data.value.list.map(item => {
      // 从控制台输出可以看到号码是空格分隔的
      const numbers = item.lotteryDrawResult.split(' ')
      // 红球部分用逗号分隔
      const redNumbers = numbers.slice(0, 5).map(num => Number(num))
      // 蓝球是单独的一个数字
      const blueNumbers =numbers.slice(5, 7).map(num => Number(num))
      
      return {
        date: item.lotteryDrawTime,
        period: item.lotteryDrawNum,
        red: redNumbers,
        blue: blueNumbers
      }
    })
    
    generatePredictions()
    calculateNextDraw()
  } catch (err) {
    error.value = `获取历史数据失败: ${err.message}`
    console.error('获取历史数据失败:', err)
  }
}

// 生成预测号码
const generatePredictions = () => {
  // 创建号码统计对象
  const stats = {
    red: new Array(35).fill(0),    // 红球统计
    blue: new Array(12).fill(0),   // 蓝球统计
    redPairs: {},                  // 红球组合统计
    redGaps: new Array(35).fill(0),// 红球间隔统计
    blueGaps: new Array(12).fill(0)// 蓝球间隔统计
  }
  
  // 统计历史数据
  let lastReds = []
  let lastBlues = []
  
  historyData.value.forEach(item => {
    // 统计单个号码频率
    item.red.forEach(num => stats.red[num-1]++)
    item.blue.forEach(num => stats.blue[num-1]++)
    
    // 统计红球组合
    item.red.forEach((num, i) => {
      item.red.slice(i + 1).forEach(num2 => {
        const pair = `${num},${num2}`
        stats.redPairs[pair] = (stats.redPairs[pair] || 0) + 1
      })
    })
    
    // 统计间隔
    if (lastReds.length > 0) {
      item.red.forEach(num => {
        if (lastReds.includes(num)) {
          stats.redGaps[num-1]++
        }
      })
      item.blue.forEach(num => {
        if (lastBlues.includes(num)) {
          stats.blueGaps[num-1]++
        }
      })
    }
    
    lastReds = item.red
    lastBlues = item.blue
  })
  
  // 生成5组预测号码
  predictions.value = []
  for(let i = 0; i < 5; i++) {
    // 根据历史频率和间隔选择红球
    const red = []
    while(red.length < 5) {
      // 计算每个号码的权重
      const weights = stats.red.map((freq, index) => {
        const gap = stats.redGaps[index]
        const num = index + 1
        // 根据频率、间隔和热温冷号的规律计算权重
        let weight = freq * 0.4                    // 频率权重 40%
        weight += (gap > 3 ? 1.5 : 0.5) * 0.3     // 间隔权重 30%
        weight += (lastReds.includes(num) ? 0.3 : 0.7) * 0.3  // 热温冷权重 30%
        return weight
      })
      
      // 根据权重随机选择号码
      const totalWeight = weights.reduce((a, b) => a + b, 0)
      let random = Math.random() * totalWeight
      let selectedNum = 0
      
      for (let j = 0; j < weights.length; j++) {
        random -= weights[j]
        if (random <= 0) {
          selectedNum = j + 1
          break
        }
      }
      
      if (!red.includes(selectedNum)) {
        red.push(selectedNum)
      }
    }
    
    // 根据历史频率和间隔选择蓝球
    const blue = []
    while(blue.length < 2) {
      const weights = stats.blue.map((freq, index) => {
        const gap = stats.blueGaps[index]
        const num = index + 1
        let weight = freq * 0.4
        weight += (gap > 2 ? 1.5 : 0.5) * 0.3
        weight += (lastBlues.includes(num) ? 0.3 : 0.7) * 0.3
        return weight
      })
      
      const totalWeight = weights.reduce((a, b) => a + b, 0)
      let random = Math.random() * totalWeight
      let selectedNum = 0
      
      for (let j = 0; j < weights.length; j++) {
        random -= weights[j]
        if (random <= 0) {
          selectedNum = j + 1
          break
        }
      }
      
      if (!blue.includes(selectedNum)) {
        blue.push(selectedNum)
      }
    }
    
    red.sort((a, b) => a - b)
    blue.sort((a, b) => a - b)
    predictions.value.push({ red, blue })
  }
}

// 生成图片
const generateImage = async () => {
  if (!predictionRef.value) return
  try {
    const canvas = await html2canvas(predictionRef.value)
    const image = canvas.toDataURL('image/png')
    const link = document.createElement('a')
    link.href = image
    link.download = '双色球预测结果.png'
    link.click()
  } catch (error) {
    ElMessage.error('生成图片失败')
  }
}

// 复制图片
const copyImage = async () => {
  if (!predictionRef.value) return
  try {
    const canvas = await html2canvas(predictionRef.value)
    canvas.toBlob(async (blob) => {
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': blob })
      ])
      ElMessage.success('复制成功')
    })
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

onMounted(() => {
  fetchHistoryData()
})
</script>

<style scoped>
.lottery-container {
  padding: 20px;
  position: relative;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.left-section {
  flex: 1;
  min-width: 0;
}

.right-section {
  width: 380px;
  flex-shrink: 0;
}

.prediction-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.prediction-content {
  margin: 20px 0;
}

.prediction-item {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 6px;
  background: #f8f9fa;
}

.prediction-number {
  display: flex;
  align-items: center;
  gap: 4px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.ball {
  display: inline-block;
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  border-radius: 50%;
  margin: 0 4px;
  color: white;
  font-weight: bold;
  font-size: 14px;
}

.red {
  background-color: #f56c6c;
}

.blue {
  background-color: #409eff;
  margin-left: 12px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.prediction-header {
  margin-bottom: 20px;
}

.prediction-header h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.next-draw-info {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 14px;
}

.next-draw-info span {
  background: #f0f2f5;
  padding: 4px 8px;
  border-radius: 4px;
}

@media (max-width: 1200px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .right-section {
    width: 100%;
  }
}
</style> 